#import <appkit/appkit.h>
#import "Controller.h"

@implementation Controller

-loadNewTool:sender
{
	OpenPanel  *openPanel;
	id newClass, newItem, newCell, newIcon;
	id newBundle;
	const char *fileTypes[2] = {"bundle",NULL};
	char fullName[MAXPATHLEN+1];
	int newTag;
	const char *bundleName;
	NXRect r;
	
	/* Get an OpenPanel and get the filename of the desired bundle. */
	openPanel = [OpenPanel new];
	if( ![openPanel runModalForTypes:fileTypes] ) return self;          //leave if Cancel or none
	bundleName = [openPanel filename];

	/* Get new bundle and the class object in it. */
	newBundle = [[NXBundle alloc] initForDirectory:bundleName];
	if( (newClass = [newBundle principalClass]) == nil) return self;    //leave if no class
	
	/* Give the new class to the draw view as a new draw class. */
	newTag = [drawView addShapeClass:newClass];

	/* Add corresponding item to Tools menu, and set action, target, tag. */
	newItem = [toolsMenu	addItem:[newClass name]
							action:@selector(takeDrawTypeFrom:)
							keyEquivalent:0]; 
	[newItem setTarget:self];
	[newItem setTag:newTag];
	[toolsMenu display];
	
	/* Add button with icon to the Tools palette, and set tag. */
	/* First, get path to the tiff file with the palette icon. */
	if( [newBundle		getPath:fullName
					forResource:[newClass name]
					ofType:"tiff"]) {
	
		/* Now get the icon and stick on a new buttoncell in the matrix. */
		if(newIcon=[[NXImage alloc] initFromFile:fullName]){
			[toolPalette addCol];
			newCell=[toolPalette cellAt:0 :([toolPalette cellCount]-1)];
			[[newCell	setTag:newTag]
						setImage:newIcon];

			/* Finally, resize matrix and window to hold new cell. */
			[toolPalette sizeToCells];
			[toolPalette getFrame:&r];
			[[toolPalette window] sizeWindow:r.size.width :r.size.height];
			[toolPalette moveTo:0.0 :0.0];
			[[toolPalette window] display];
		}
	}
		
	return self; 
}

-takeDrawTypeFrom:sender
{
	int tag=[sender selectedTag];
	[drawView setDrawType:tag];
	[toolPalette selectCellWithTag:tag];     //in case from menu, select also in palette
	return self;
}

@end 
